import { Injectable, InternalServerErrorException } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { getConnection, Repository } from "typeorm";
import {
  GetGoodsDetailsDto,
  GetGoodsDto,
  GetGoodsListDto,
  GetGoodsTypeDto,
} from "../dto/goods.dto";
import { Goods } from "/@/entities/goods/Goods.entity";
import { GoodsType } from "/@/entities/goods/GoodsType.entity";
import { Collect } from "/@/entities/operate/Collect.entity";
@Injectable()
export class WeappGoodsService {
  constructor(
    @InjectRepository(Collect)
    private collectRepository: Repository<Collect>,
    @InjectRepository(GoodsType)
    private goodsTypeRepository: Repository<GoodsType>,
    @InjectRepository(Goods)
    private goodsRepository: Repository<Goods>,
  ) {
    //
  }
  /**
   * 获取商品分类
   * @param params 字段
   */
  async getGoodsTypeByPid(query: GetGoodsTypeDto) {
    const { pid } = query;
    try {
      let qb = this.goodsTypeRepository.createQueryBuilder("goodsType");
      qb = qb
        .orderBy("goodsType.name", "DESC")
        .where("goodsType.pid = :pid", { pid });
      const data = await qb.getMany();
      return data;
    } catch (error) {
      throw new InternalServerErrorException("查询失败");
    }
  }

  /**
   * 获取商品列表，根据搜索字段 什么都不传则根据推荐指数
   * @param query 字段
   */
  async getGoodsList(query: GetGoodsListDto) {
    // 获取请求参数
    const { pageSize = 20, page = 1, text = "" } = query;
    try {
      let qb = this.goodsRepository.createQueryBuilder("goods");
      qb = qb
        .skip(pageSize * (page - 1))
        .take(pageSize)
        .orderBy("goods.recommend", "DESC")
        .where("goods.status = :status", { status: "1" })
        .andWhere("goods.stock > :stock", { stock: 0 });
      // 如果有传参数的字段，则在名称，简介，标签中都进行模糊查询  并且是根据推荐值排序的
      if (text) {
        qb = qb
          .andWhere("goods.name like :name", { name: "%" + text + "%" })
          .orWhere("goods.brief like :brief", { brief: "%" + text + "%" })
          .orWhere("goods.label like :label", { label: "%" + text + "%" });
      }
      // 该页数据已经总数返回
      const [items, total] = await qb.getManyAndCount();
      return { items, total };
    } catch (error) {
      throw new InternalServerErrorException("查询失败");
    }
  }

  /**
   * 获取商品列表 根据type
   * @param query 字段
   */
  async getGoodsListByType(query: GetGoodsDto) {
    const { pageSize = 20, page = 1, id } = query;
    try {
      const [items, total] = await this.goodsRepository
        .createQueryBuilder("goods")
        .andWhere((qb) => {
          const subQuery = qb
            .subQuery()
            .from(
              "goods_goods_types_goods_type",
              "goods_goods_types_goods_type",
            )
            .select("goods_goods_types_goods_type.goodsId")
            .where("goods_goods_types_goods_type.goodsTypeId = :goodsTypeId")
            .getQuery();
          return "goods.id in " + subQuery;
        })
        .skip(pageSize * (page - 1))
        .take(pageSize)
        .setParameter("goodsTypeId", id)
        .orderBy("goods.recommend", "DESC")
        .andWhere("goods.status = :status", { status: "1" })
        .getManyAndCount();
      return { items, total };
    } catch (error) {
      console.log(error);
      throw new InternalServerErrorException("查询失败");
    }
  }

  /**
   * 获取商品详情
   * @param query 字段
   */
  async getGoodsDetails(query: GetGoodsDetailsDto, user: any) {
    const { id } = query;
    const { id: user_id } = user;
    try {
      const data: any = await this.goodsRepository.findOne({ id });
      const collect = await this.collectRepository.findOne({
        goods_id: id.toString(),
        user_id,
      });
      if (collect) {
        data.collect = collect.id;
      }
      return data;
    } catch (error) {
      throw new InternalServerErrorException("查询失败");
    }
  }
}
